package com.google.code.gestion_de_conferences;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

 
public class RegisterActivity extends Activity {
	
	AABDatabaseManager db;
	Button register_btn;
	EditText reg_fullname,reg_phone,reg_username,reg_password,reg_confirm_password;
	TextView reg_fullname_error,  reg_phone_error ,reg_username_error ,reg_password_error ,reg_confirm_password_error;
	int editAdmin;

	/**
	 * @author Rayan Zahab
	 * @param Bundle
	 */
	@Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Set View to register.xml
        setContentView(R.layout.register);
       
        db = new AABDatabaseManager(this);
        
        register_btn = (Button) findViewById(R.id.btn_register);
        reg_fullname = (EditText) findViewById(R.id.reg_fullname);
        reg_phone = (EditText) findViewById(R.id.reg_phone);
        reg_username = (EditText) findViewById(R.id.reg_username);
        reg_password = (EditText) findViewById(R.id.reg_password);
        reg_confirm_password = (EditText) findViewById(R.id.reg_confirm_password);
        reg_confirm_password_error = (TextView) findViewById(R.id.reg_confirm_password_error);
        reg_password_error = (TextView) findViewById(R.id.reg_password_error);
        reg_fullname_error = (TextView) findViewById(R.id.reg_fullname_error);
        reg_username_error = (TextView) findViewById(R.id.reg_username_error);
        reg_phone_error = (TextView) findViewById(R.id.reg_phone_error);
       
        
        //This is to get the editAdmin variable
        Intent i = getIntent(); 
        
        //0 is the default value of the selectedUserId. This value will specify that no user was selected
        editAdmin = i.getIntExtra("editAdmin", 0);    
       
        //we are editing a user
        if (editAdmin != 0)
        {	
        	//change the activity title
        	setTitle("Edit admin profile");
        	
        	//set a warning message f
        	TextView reg_warning_msg = (TextView) findViewById(R.id.reg_warning_msg);
        	reg_warning_msg.setText("If you don't want to change your password no need to set a value for it");
        	
        	//change button text
        	register_btn.setText("Edit profile");
        	
        	//populate form with correct data if we are editing the user
        	populateForm();
        	
        }
        
         register_btn.setOnClickListener
    	(
    		new View.OnClickListener()
	    	{
				@Override public void onClick(View v) 
				{
					String name = reg_fullname.getText().toString();
			    	String phone = reg_phone.getText().toString();
			    	String username = reg_username.getText().toString();
			    	String pass = reg_password.getText().toString();
			    	String pass2 = reg_confirm_password.getText().toString();
			    	String is_admin="1";
					register( name,  username,  pass,  pass2,  phone, is_admin);
				}
			}
    	);     
    }
	
	/**
	 * This function validates an email address format
	 * 
	 * @author Moustafa Chouraiki 
	 * 
	 * @param target mail to validate
	 * @return boolean
	 */
	 public final static boolean isValidEmail(CharSequence target)
	 {
	     if (target == null) 
	     {
	         return false;
	      }
	     else
	     {
	         return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
	     }
     }
	 
	/**
	 * This function validates the data sent on register and display the related error message
	 * 
	 * @author Hyame Alameddine <hyame.alameddine@gmail.com>
	 * @author Rayan Zahab 
	 * 
	 * @param name
	 * @param username
	 * @param pass
	 * @param pass2
	 * @param phone
	 * 
	 * @return Boolean
	 */
	private Boolean validate(String name, String username, String pass, String pass2, String phone)
    {
        //first clear all error fields 
        clearErrors();
      
        Boolean error = false;
       
        if(name.length()<4)
        {
            error = true;
            reg_fullname_error.setText( "Name is minimum 4 digits!");
        }
      
        if(phone.length()!=8)
        {
            error = true;
            reg_phone_error.setText(  "Phone must be 8 digits!");
        }
        
        User u=new User();
		u.setEmail(username);
       
        //check if there is users that have the same email
        ArrayList<String> rowArray = db.getRowAsArrayByUser(u);
        
        //we are editing a user
        if (editAdmin != 0 && rowArray.size()>0)
        {
        	ArrayList<ArrayList<Object>> result = new ArrayList<ArrayList<Object>>();
			
			//get the admin user object from the db
			result = db.getRowAsArrayByPosition(6,"User", 1+"");
			 
			//get the admin data
			 ArrayList<Object> editedUser = result.get(0);
        	  
        	  //check if the user having the same username is the edited user so we dont display the msg
        	  if(!editedUser.get(0).equals(rowArray.get(0)))
        	  {
        		  error = true;
        		  reg_username_error.setText("Username already exist!"); 
        		  
        	  }
        	  System.out.println(rowArray);
        }
        else
        {
        	 if(rowArray.size()>0)
             {
                 error = true;
                 reg_username_error.setText("Username already exist!");      
             }
    	}
       
       
        if(username.length()<6)
        {
            error = true;
            reg_username_error.setText("User is minimum 6 digits!");
        }
        if(!isValidEmail(username.toString())) 
        {
                error = true;
                reg_username_error.setText("Email address is not Formatted !");
                
        }
        if (pass.length()<6)
        {
            error = true;
            reg_password_error.setText( "Password'length is minimum 6!");
        }
       
        if(!pass.equals(pass2))
        {
            error =true;
            reg_confirm_password_error.setText( "Passwords don't match!");
        }

        return error;
    }
	
/**
	 * This function register a new Admin account into the DB
	 * 
	 * @author Rayan Zahab <differentruna@gmail.com> 
	 * @author Hyame Alameddine <hyame.alameddine@gmail.com>
	 * 
	 * @param name
	 * @param username
	 * @param pass
	 * @param pass2
	 * @param phone
	 * @param is_admin
	 */
 private void register(String name, String username, String pass, String pass2, String phone, String is_admin)
 {
	    //if no password entered keep the old password
	 	if(pass.length()== 0 && pass2.length()== 0 && editAdmin != 0)
		{	
	 		ArrayList<ArrayList<Object>> result = new ArrayList<ArrayList<Object>>();
			
			//get the admin user object from the db
			result = db.getRowAsArrayByPosition(6,"User", 1+"");
			 
			//get the admin data
			 ArrayList<Object> dbUser = result.get(0);
			
			pass = dbUser.get(5).toString();
			pass2 = dbUser.get(5).toString();
		}
			 	
    	Boolean error = validate( name,  username,  pass,  pass2,  phone);
    	
    	if(!error)
    	{
    		try
    		{    			
    			User u=new User();
    			u.setFullName(name);
    			u.setEmail(username);
    			u.setIsAdmin("1");
    			u.setPassword(pass);
    			u.setPhoneNumber(phone);
    			u.setCompany("Admin");
    			
    			//Check if we are editing the admin
    			if (editAdmin != 0)
    			{		
    				ArrayList<ArrayList<Object>> result = new ArrayList<ArrayList<Object>>();
    				
    				//get the admin user object from the db
    				result = db.getRowAsArrayByPosition(6,"User", 1+"");
    				 
    				//get the admin data
    				ArrayList<Object> dbUser = result.get(0);
    				 
    				//set the user id to edit
    				u.setID(Integer.parseInt(dbUser.get(0).toString()));
    				    				
    				//update row
    				db.updateRow (u);
    				
    				//success msg
    				Toast.makeText(this, "Your profile is successfully edited", Toast.LENGTH_LONG).show();
    				
    				//redirect to rooms page
    				Intent i = new Intent(getApplicationContext(), RoomsListActivity.class);
        	        startActivity(i);
  		         
    			}		
    			else
    			{	    			
	    			db.insertRow(u); 
	    			Toast.makeText(this, "You are successfully registered", Toast.LENGTH_LONG).show();
	    			
	    			//redirect to login page
	    			Intent i = new Intent(getApplicationContext(), LoginActivity.class);
	    	        startActivity(i);
    			}

    	    	
        	}
    		catch (Exception e)
        	{
        		Log.e("Update Error", e.toString());
        		e.printStackTrace();
        	}
    	}
    	
    }	
 
 	/**
	 * This function will populate the registraion form with the admin data
	 * 
	 * @author Hyame Alameddine <hyame.alameddine@gmail.com>
	 * 
	 */
	private void populateForm ()
	{	 		
		ArrayList<ArrayList<Object>> result = new ArrayList<ArrayList<Object>>();
		
		//get the user object from the db
		 result = db.getRowAsArrayByPosition(6,"User", 1+"");
		
		 //get the admin data
		 ArrayList<Object> dbUser = result.get(0);
		
		 //populate the form
		 reg_fullname.setText(dbUser.get(1).toString()); 
		 reg_username.setText(dbUser.get(2).toString());
		 reg_phone.setText(dbUser.get(4).toString());
		 
		 	 		
		
	}
 
 /**
	 * This function clears all errors in register page
	 * @author Rayan Zahab <differentruna@gmail.com> 
	 */
	private void clearErrors()
	{
        reg_fullname_error.setText( "");
        reg_phone_error.setText(  "");
        reg_username_error.setText("");
        reg_password_error.setText( "");        
        reg_confirm_password_error.setText( "");
    }
	/**
	 * This function create the menu options 
	 * @author Rayan Zahab <differentruna@gmail.com> 
	 * @param menu
	 */
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.no_login_menu, menu);              
        return true;
    }
    /**
	   * This function handles clicking any of the menu's items
	   * @author Rayan Zahab <differentruna@gmail.com> 
	   * @author Hyame Alameddine <hyame.alameddine@gmail.com>
	   * @param menu
	   */
	 @Override
	 public boolean onOptionsItemSelected(MenuItem item) 
	  {	  
		  switch (item.getItemId()) 
		  {
	          case R.id.help:     
	                AlertDialog alertDialog = new AlertDialog.Builder(this).create();
	                alertDialog.setTitle("Help!");
	                alertDialog.setMessage("Gestion de conference is an application helps you manage reservations, add rooms ,add users and reserve rooms to organize conferences !");
	                alertDialog.setIcon(R.drawable.icon);
	                alertDialog.show();
	                break;
	          case R.id.developers: 
	            	Toast.makeText(this, "Rayan,Hyam,Mostafa!", Toast.LENGTH_LONG).show();
	                break;
	            
	        }
	        return true;
	    }
    
}
